<!DOCTYPE html>
{% load static %}
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实验室门禁系统 - 控制面板</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #4e73df;
            --secondary-color: #1cc88a;
            --danger-color: #e74a3b;
            --warning-color: #f6c23e;
            --info-color: #36b9cc;
        }
        
        body {
            font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fc;
        }
        
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(180deg, var(--primary-color) 10%, #224abe 100%);
            color: white;
            position: fixed;
            width: 250px;
        }
        
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 1rem;
            transition: all 0.2s;
        }
        
        .sidebar .nav-link:hover {
            color: white;
            background-color: rgba(255, 255, 255, 0.1);
        }
        
        .sidebar .nav-link.active {
            color: white;
            font-weight: bold;
        }
        
        .sidebar .sidebar-brand {
            height: 4.375rem;
            text-decoration: none;
            font-size: 1.2rem;
            font-weight: 800;
            padding: 1.5rem 1rem;
            text-align: center;
            letter-spacing: 0.05rem;
            color: white;
        }
        
        .main-content {
            margin-left: 250px;
            padding: 1.5rem;
        }
        
        .card {
            border: none;
            border-radius: 0.35rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            margin-bottom: 1.5rem;
        }
        
        .card-header {
            background-color: #f8f9fc;
            border-bottom: 1px solid #e3e6f0;
            padding: 0.75rem 1.25rem;
        }
        
        .card-header h6 {
            font-weight: 700;
            margin: 0;
            color: #4e73df;
        }
        
        .card-body {
            padding: 1.25rem;
        }
        
        .data-card {
            border-left: 0.25rem solid var(--primary-color);
        }
        
        .data-card.temp {
            border-left-color: var(--danger-color);
        }
        
        .data-card.humidity {
            border-left-color: var(--info-color);
        }
        
        .data-card.light {
            border-left-color: var(--warning-color);
        }
        
        .data-card.card-count {
            border-left-color: var(--secondary-color);
        }
        
        .data-card .card-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #5a5c69;
        }
        
        .data-card .card-icon {
            font-size: 2rem;
            opacity: 0.3;
        }
        
        .table-responsive {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .user-info {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 1rem;
        }
        
        .user-info .user-name {
            font-weight: bold;
            font-size: 1.1rem;
        }
        
        .door-controls {
            display: flex;
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .door-btn {
            flex: 1;
            padding: 1rem;
            border: none;
            border-radius: 0.35rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .door-btn.open {
            background-color: var(--secondary-color);
            color: white;
        }
        
        .door-btn.close {
            background-color: var(--danger-color);
            color: white;
        }
        
        .door-btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                min-height: auto;
            }
            
            .main-content {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <a href="#" class="sidebar-brand">
            <i class="bi bi-shield-lock"></i> 实验室门禁系统
        </a>
        
        <div class="user-info">
            <div class="user-name">{{ username }}</div>
            <small>欢迎回来</small>
        </div>
        
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link active" href="{% url 'back:dashboard' %}">
                    <i class="bi bi-speedometer2 me-2"></i> 控制面板
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{% url 'back:write_card' %}">
                    <i class="bi bi-credit-card me-2"></i> 卡片录入
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{% url 'back:write_finger' %}">
                    <i class="bi bi-fingerprint me-2"></i> 指纹录入
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{% url 'back:write_password' %}">
                    <i class="bi bi-key me-2"></i> 密码设置
                </a>
            </li>
            <li class="nav-item mt-5">
                <a class="nav-link" href="{% url 'back:logout' %}">
                    <i class="bi bi-box-arrow-right me-2"></i> 退出登录
                </a>
            </li>
        </ul>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0 text-gray-800">控制面板</h1>
            <div id="current-time" class="text-muted"></div>
        </div>
        
        <!-- 数据卡片 -->
        <div class="row">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card data-card temp h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">温度</div>
                                <div class="card-value">{{ environment_data.0.temperature|default:"--" }} °C</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-thermometer-half card-icon text-danger"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card data-card humidity h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">湿度</div>
                                <div class="card-value">{{ environment_data.0.humidity|default:"--" }} %</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-droplet-half card-icon text-info"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card data-card light h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">光照</div>
                                <div class="card-value">{{ environment_data.0.light|default:"--" }} lux</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-brightness-high card-icon text-warning"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card data-card card-count h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">今日刷卡数据</div>
                                <div class="card-value">{{ card_data|length }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-credit-card card-icon text-success"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 在门禁控制区块后面添加实验室开锁按钮 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold">实验室门禁控制</h6>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-12">
                                <h6 class="font-weight-bold">T栋实验室</h6>
                            </div>
                            <div class="col-md-12">
                                <div class="d-flex flex-wrap gap-2">
                                    <button class="btn btn-danger m-1" style="font-size: 1.1rem; font-weight: bold;" onclick="controlLabDoor('T101')">
                                        <i class="bi bi-door-open me-1"></i> T101 (当前设备)
                                    </button>
                                    <button class="btn btn-success m-1" onclick="controlLabDoor('T102')">
                                        <i class="bi bi-door-open me-1"></i> T102
                                    </button>
                                    <button class="btn btn-success m-1" onclick="controlLabDoor('T103')">
                                        <i class="bi bi-door-open me-1"></i> T103
                                    </button>
                                    <button class="btn btn-success m-1" onclick="controlLabDoor('T104')">
                                        <i class="bi bi-door-open me-1"></i> T104
                                    </button>
                                    <button class="btn btn-success m-1" onclick="controlLabDoor('T105')">
                                        <i class="bi bi-door-open me-1"></i> T105
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <h6 class="font-weight-bold">S栋实验室</h6>
                            </div>
                            <div class="col-md-12">
                                <div class="d-flex flex-wrap gap-2">
                                    <button class="btn btn-primary m-1" onclick="controlLabDoor('S101')">
                                        <i class="bi bi-door-open me-1"></i> S101
                                    </button>
                                    <button class="btn btn-primary m-1" onclick="controlLabDoor('S102')">
                                        <i class="bi bi-door-open me-1"></i> S102
                                    </button>
                                    <button class="btn btn-primary m-1" onclick="controlLabDoor('S103')">
                                        <i class="bi bi-door-open me-1"></i> S103
                                    </button>
                                    <button class="btn btn-primary m-1" onclick="controlLabDoor('S104')">
                                        <i class="bi bi-door-open me-1"></i> S104
                                    </button>
                                    <button class="btn btn-primary m-1" onclick="controlLabDoor('S105')">
                                        <i class="bi bi-door-open me-1"></i> S105
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <p>操作状态: <span id="lab-door-status" class="badge bg-secondary">等待操作</span></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- RFID卡片信息 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="m-0 font-weight-bold">RFID卡片信息</h6>
                        <span id="rfid-status" class="badge bg-secondary">等待读卡...</span>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="text-xs font-weight-bold text-uppercase mb-1">卡号 (UID):</label>
                                    <div id="card-uid" class="h5 mb-0 font-weight-bold text-gray-800">--</div>
                                </div>
                                <div class="mb-3">
                                    <label class="text-xs font-weight-bold text-uppercase mb-1">卡片类型:</label>
                                    <div id="card-type" class="h5 mb-0 font-weight-bold text-gray-800">--</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="text-xs font-weight-bold text-uppercase mb-1">读取时间:</label>
                                    <div id="read-time" class="h5 mb-0 font-weight-bold text-gray-800">--</div>
                                </div>
                                <div class="mb-3">
                                    <label class="text-xs font-weight-bold text-uppercase mb-1">状态:</label>
                                    <div id="read-status" class="h5 mb-0 font-weight-bold text-gray-800">--</div>
                                </div>
                            </div>
                        </div>
                        <!-- 添加最近刷卡记录部分 -->
                        <div class="mt-4">
                            <h6 class="mb-3 font-weight-bold">最近刷卡记录</h6>
                            <div id="recent-card-records" class="border p-3 rounded" style="max-height: 200px; overflow-y: auto;">
                                <div class="text-center text-muted">暂无刷卡记录</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- RFID卡管理 - 移到这里 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold">RFID卡管理</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <button class="btn btn-primary" onclick="enrollRFID()">
                                <i class="bi bi-save me-2"></i>录入持卡人信息
                            </button>
                            <div class="mt-3">
                                <input type="text" id="card-remark" class="form-control" 
                                       placeholder="输入持卡人姓名">
                            </div>
                        </div>
                        <!-- 当前检测状态 -->
                        <p>当前检测状态: <span id="rfid-management-status" class="badge bg-secondary">未知</span></p>
                        
                        <!-- 显示当前已录入的卡片数量 -->
                        <div class="mt-3">
                            <p>已录入卡片数量: <span id="card-count" class="badge bg-info">加载中...</span></p>
                            <button class="btn btn-sm btn-info" onclick="fetchCardList()">
                                <i class="bi bi-arrow-clockwise me-1"></i>刷新卡片列表
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="row">
            <!-- 今日刷卡数据 - 占据整行 -->
            <div class="col-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold">今日刷卡数据</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive" style="max-height: 500px;">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>刷卡时间</th>
                                        <th>持卡人</th>
                                        <th>卡号(UID)</th>
                                        <th>卡片类型</th>
                                        <th>注册状态</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for card in card_data %}
                                    <tr>
                                        <td>{{ card.timestamp|date:"Y-m-d H:i:s" }}</td>
                                        <td>
                                            {% if card.information %}
                                            <span class="font-weight-bold text-success">{{ card.information }}</span>
                                            {% else %}
                                            <span class="text-muted">未知</span>
                                            {% endif %}
                                        </td>
                                        <td>{{ card.card_number }}</td>
                                        <td>{{ card.card_type|default:"MIFARE" }}</td>
                                        <td>
                                            {% if card.is_registered %}
                                            <span class="badge bg-success">已注册</span>
                                            {% else %}
                                            <span class="badge bg-warning">未注册</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% empty %}
                                    <tr>
                                        <td colspan="5" class="text-center">暂无数据</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 环境数据历史 - 放在后面 -->
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold">环境数据历史</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>时间</th>
                                        <th>温度 (°C)</th>
                                        <th>湿度 (%)</th>
                                        <th>光照 (lux)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for data in environment_data %}
                                    <tr>
                                        <td>{{ data.timestamp|date:"Y-m-d H:i:s" }}</td>
                                        <td>{{ data.temperature }}</td>
                                        <td>{{ data.humidity }}</td>
                                        <td>{{ data.light }}</td>
                                    </tr>
                                    {% empty %}
                                    <tr>
                                        <td colspan="4" class="text-center">暂无数据</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 实时卡片数据显示 -->
    <script>
    function updateCardTable(data) {
        const tableBody = document.getElementById('card-data-body');
        tableBody.innerHTML = data.map(card => `
            <tr>
                <td>${card.card_number}</td>
                <td>MIFARE Classic</td>
                <td>${new Date(card.timestamp).toLocaleString()}</td>
                <td>${card.information ? '已注册' : '未注册'}</td>
                <td>${card.information || ''}</td>
            </tr>
        `).join('');
    }

    function fetchCardData() {
        fetch('/back/get_rfid_info/')
            .then(response => response.json())
            .then(data => {
                // 更新卡片表格
                updateCardTable(data);

                // 更新最近刷卡记录
                let container = document.getElementById('recent-card-records');
                if (data.length > 0) {
                    container.innerHTML = data.map(item => 
                        `<div class="card-item mb-2">
                            <span class="badge badge-info text-white" style="background-color: #17a2b8;">${new Date(item.timestamp).toLocaleTimeString()}</span>
                            ${item.card_number} - 
                            <span class="text-${item.information ? 'success font-weight-bold' : 'muted'}">
                                ${item.information || '未知持卡人'}
                            </span>
                        </div>`
                    ).join('');
                } else {
                    container.innerHTML = '<div class="text-center text-muted">暂无刷卡记录</div>';
                }
            });
    }
    
    // 初始化轮询（每1秒刷新）
    setInterval(fetchCardData, 1000);
    fetchCardData(); // 立即获取初始数据
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 更新时间
        function updateTime() {
            const now = new Date();
            const options = { 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric', 
                hour: '2-digit', 
                minute: '2-digit', 
                second: '2-digit' 
            };
            document.getElementById('current-time').textContent = now.toLocaleDateString('zh-CN', options);
        }
        
        updateTime();
        setInterval(updateTime, 1000);
        
        // 门禁控制
        function controlDoor(action) {
            fetch('/door_control/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({
                    action: action,
                    value: 1
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('door-status').textContent = action === 'open' ? '已开启' : '已关闭';
                    document.getElementById('door-status').className = action === 'open' ? 'badge bg-success' : 'badge bg-danger';
                    alert(data.message);
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请检查网络连接');
            });
        }
        
        // RFID卡片信息获取
        function fetchRFIDCardInfo(mode = 'realtime') {
            const formData = new FormData();
            const cardRemark = document.getElementById('card-remark').value.trim();
            formData.append('information', cardRemark);
        
            fetch(`/back/get_rfid_info/?mode=${mode}`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: mode === 'enroll' ? formData : null
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success' && data.card_detected) {
                    // 更新RFID卡片信息
                    document.getElementById('card-uid').textContent = data.uid || '--';
                    document.getElementById('card-type').textContent = data.card_type || '--';
                    document.getElementById('read-time').textContent = data.read_time || '--';
                    document.getElementById('read-status').textContent = data.is_registered ? '已注册' : '未注册';
                    
                    // 录入模式下执行开锁
                    if (mode === 'enroll' && data.enroll_success) {
                        controlDoor('open'); // 执行继电器开锁
                        if (cardRemark) {
                            alert(`卡号 ${data.uid} 已成功录入，持卡人: ${cardRemark}`);
                        } else {
                            alert('请输入持卡人姓名再录入卡片');
                            return;
                        }
                    }
                    
                    // 更新状态标签
                    document.getElementById('rfid-status').textContent = '已检测到卡片';
                    document.getElementById('rfid-status').className = 'badge bg-success';

                    // 刷新卡片数据以获取最新记录
                    fetchCardData();
                } else {
                    if (!data.card_detected) {
                        document.getElementById('rfid-status').textContent = '未检测到卡片';
                        document.getElementById('rfid-status').className = 'badge bg-danger';
                    }
                    if (mode === 'enroll' && !data.enroll_success) {
                        alert('录入失败: ' + (data.error || '未知错误'));
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请检查网络连接');
            });
        }
        
        // 新增录入按钮点击处理
        function enrollRFID() {
            const cardRemark = document.getElementById('card-remark').value.trim();
            if (!cardRemark) {
                alert('请输入持卡人姓名');
                return;
            }
            
            if (confirm('请将卡片放在读卡器上，点击确定开始录入持卡人信息')) {
                fetchRFIDCardInfo('enroll');
            }
        }
        
        // 页面加载完成后开始定期获取RFID信息
        document.addEventListener('DOMContentLoaded', function() {
            // 立即获取一次RFID信息
            fetchRFIDCardInfo();
            
            // 每2秒获取一次RFID信息
            setInterval(fetchRFIDCardInfo, 2000);
            
            // 加载卡片列表
            fetchCardList();
        });
        
        // 实验室门禁控制
        function controlLabDoor(labNumber) {
            const payload = {
                lab_number: labNumber,
                operation: "OPEN"
            };
            
            // 更新状态为"正在发送"
            document.getElementById('lab-door-status').textContent = `正在发送命令...`;
            document.getElementById('lab-door-status').className = 'badge bg-warning';
            
            fetch('/back/publish/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({
                    topic: '/lab_access',
                    message: JSON.stringify(payload)
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    if (labNumber === 'T101') {
                        document.getElementById('lab-door-status').textContent = `T101门禁已开启`;
                        document.getElementById('lab-door-status').className = 'badge bg-success';
                    } else {
                        document.getElementById('lab-door-status').textContent = `${labNumber}命令已发送，但只有T101设备在线`;
                        document.getElementById('lab-door-status').className = 'badge bg-info';
                    }
                    
                    // 5秒后自动将状态重置
                    setTimeout(() => {
                        document.getElementById('lab-door-status').textContent = '等待操作';
                        document.getElementById('lab-door-status').className = 'badge bg-secondary';
                    }, 5000);
                } else {
                    document.getElementById('lab-door-status').textContent = `${labNumber} 操作失败`;
                    document.getElementById('lab-door-status').className = 'badge bg-danger';
                    alert(`操作失败: ${data.message || '未知错误'}`);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('lab-door-status').textContent = `${labNumber} 操作失败`;
                document.getElementById('lab-door-status').className = 'badge bg-danger';
                alert('操作失败，请检查网络连接');
            });
        }

        // 获取已录入的卡片列表
        function fetchCardList() {
            document.getElementById('card-count').textContent = '正在请求...';
            document.getElementById('card-count').className = 'badge bg-warning';
            
            // 1. 首先请求ESP32发送卡片列表
            fetch('/back/publish/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({
                    topic: '/getcards',
                    message: '{"action":"get"}'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('card-count').textContent = '请求已发送，等待响应';
                    document.getElementById('card-count').className = 'badge bg-info';
                    
                    // 2. 2秒后查询服务器是否收到了卡片列表
                    setTimeout(() => {
                        fetch('/back/get_card_list/')
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP错误! 状态: ${response.status}`);
                            }
                            return response.json();
                        })
                        .then(cardData => {
                            if (cardData && cardData.count !== undefined) {
                                document.getElementById('card-count').textContent = cardData.count;
                                document.getElementById('card-count').className = 'badge bg-success';
                                console.log('已录入卡片:', cardData.cards);
                            } else if (cardData && cardData.error) {
                                document.getElementById('card-count').textContent = `错误: ${cardData.error}`;
                                document.getElementById('card-count').className = 'badge bg-danger';
                                console.error('获取卡片列表错误:', cardData.error);
                            } else {
                                document.getElementById('card-count').textContent = '未知';
                                document.getElementById('card-count').className = 'badge bg-secondary';
                                console.warn('卡片列表数据格式异常:', cardData);
                            }
                        })
                        .catch(error => {
                            console.error('获取卡片列表出错:', error);
                            document.getElementById('card-count').textContent = '获取失败';
                            document.getElementById('card-count').className = 'badge bg-danger';
                        });
                    }, 2000);
                } else {
                    document.getElementById('card-count').textContent = `发送失败: ${data.message || '未知错误'}`;
                    document.getElementById('card-count').className = 'badge bg-danger';
                }
            })
            .catch(error => {
                console.error('请求发送失败:', error);
                document.getElementById('card-count').textContent = '请求失败';
                document.getElementById('card-count').className = 'badge bg-danger';
            });
        }
    </script>
</body>
</html>
